package com.bbzn.device.client.controller;

import com.alibaba.fastjson.JSONObject;
import com.bbzn.device.client.vo.req.*;
import com.bbzn.device.client.aspect.OperationAnnotation;
import com.bbzn.device.client.config.EmqCode;
import com.bbzn.device.client.constant.*;
import com.bbzn.device.client.dataobject.SystemParam;
import com.bbzn.device.client.exception.DefinitException;
import com.bbzn.device.client.service.CommonService;
import com.bbzn.device.client.service.OptHisService;
import com.bbzn.device.client.service.PublishService;
import com.bbzn.device.client.service.SystemParamByCacheService;
import com.bbzn.device.client.utils.*;
import io.swagger.annotations.Api;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author wulongbo
 * @Date 2021/4/23 11:58
 * @Version 1.0
 */
@RestController
@Api(value = "Publish", tags = "发布消息")
//@CrossOrigin
@RequestMapping("/publish")
public class PublishController extends BaseApiService {


    @Autowired
    private CommonService commonService;

    @Autowired
    private SystemParamByCacheService systemParamByCacheService;

    @Autowired
    private OptHisService optHisService;

    @Autowired
    private PublishService publishService;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * GPS单次定位
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/gpsSinglePosition", method = RequestMethod.POST)
    @OperationAnnotation(content = "GPS单次定位")
    public BaseResponse gpsSinglePosition(@RequestBody FenVO fenVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;

        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        String imei = fenVO.getImei();
        if (!OptionalBean.ofNullable(imei).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_IMEI_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        // 发送消息 【gps单次定位】
        // 组装json
        JSONObject data = new JSONObject();
        data.put("code", EmqCode.gpsCode);
        // 主键id-->只有这条是接收topic需要用到的
        data.put("imei", imei);
        // 推送绑定围栏topic给设备
        publishService.sendToMqtt(data.toJSONString(), EmqCode.sendTopic + imei + EmqCode.endTopic);
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }


    /**
     * GPS实时定位
     *
     * @param cusFenVO
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/pgsContinuousPosition", method = RequestMethod.POST)
    @OperationAnnotation(content = "GPS实时定位")
    public BaseResponse pgsContinuousPosition(@RequestBody FenVO cusFenVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;

        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        String imei = cusFenVO.getImei();
        if (!OptionalBean.ofNullable(imei).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_IMEI_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        // 发送消息 【GPS实时定位】
        // 组装json
        JSONObject data = new JSONObject();
        data.put("code", EmqCode.gpsContinueCode);
        // 主键id-->只有这条是接收topi
        //
        // c需要用到的
        data.put("imei", imei);
        // 推送绑定围栏topic给设备
        publishService.sendToMqtt(data.toJSONString(), EmqCode.sendTopic + imei + EmqCode.endTopic);
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }


    /**
     * 开启腾讯视频通话
     *
     * @param reqVO
     * @param request
     * @return
     * @throws Exception
     */
    @OperationAnnotation(content = "开启腾讯视频通话")
    @RequestMapping(value = "/videoCall", method = RequestMethod.POST)
    public BaseResponse videoCall(@RequestBody VideoCallVO reqVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (!OptionalBean.ofNullable(reqVO.getRoomId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(VideoCallConstant.VIDEO_CALL_ENUM, VideoCallConstant.VIDEO_CALL_UN_ROOM_ID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.isHide()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(VideoCallConstant.VIDEO_CALL_ENUM, VideoCallConstant.VIDEO_CALL_UN_IS_HIDE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        String imei = reqVO.getImei();
        if (!OptionalBean.ofNullable(imei).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_IMEI_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        // 发送消息 【开启腾讯视频通话 】
        // 组装json
        JSONObject data = new JSONObject();
        data.put("code", EmqCode.videoCallCode);
        // 主键id-->只有这条是接收topic需要用到的
        data.put("imei", imei);
        data.put("roomId", reqVO.getRoomId());
        data.put("isHide", reqVO.isHide());
        // 推送绑定围栏topic给设备
        publishService.sendToMqtt(data.toJSONString(), EmqCode.sendTopic + imei + EmqCode.endTopic, 0);
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }


    /**
     * 多人开启菊风视频或语音通话
     *
     * @param reqVO
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/manyVideoCallToJuphoon", method = RequestMethod.POST)
    @OperationAnnotation(content = "多人开启菊风视频或语音通话")
    public BaseResponse manyVideoCallToJuphoon(@RequestBody ManyVideoCallVO reqVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        List<String> imeis = reqVO.getImeis();
        if (CollectionUtils.isEmpty(imeis)) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_IMEI_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getRoomId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(VideoCallConstant.VIDEO_CALL_ENUM, VideoCallConstant.VIDEO_CALL_UN_ROOM_ID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.isHide()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(VideoCallConstant.VIDEO_CALL_ENUM, VideoCallConstant.VIDEO_CALL_UN_IS_HIDE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.isVideo()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(VideoCallConstant.VIDEO_CALL_ENUM, VideoCallConstant.VIDEO_CALL_UN_IS_VIDEO_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        imeis.stream().forEach(
                imei -> {
                    JSONObject data = new JSONObject();
                    data.put("code", EmqCode.VoiceCode);
                    // 主键id-->只有这条是接收topic需要用到的
                    data.put("imei", imei);
                    data.put("roomId", reqVO.getRoomId());
                    data.put("isHide", reqVO.isHide());
                    data.put("video", reqVO.isVideo());
                    // 推送绑定围栏topic给设备
                    publishService.sendToMqtt(data.toJSONString(), EmqCode.sendTopic + imei + EmqCode.endTopic);
                }
        );
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }


    /**
     * 手机拨号手表-发送语音(APP-手表)
     *
     * @param reqVO
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/appDialWatchByVoice", method = RequestMethod.POST)
    @OperationAnnotation(content = "手机拨号手表-发送语音(APP-手表)")
    public BaseResponse appDialWatchByVoice(@RequestBody DialVO reqVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;

        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (!OptionalBean.ofNullable(reqVO.getImei()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DialConstant.DIAL_ENUM, DialConstant.DIAL_UN_IMEI_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getCallUserId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DialConstant.DIAL_ENUM, DialConstant.DIAL_UN_CALL_USER_ID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getCallUserName()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DialConstant.DIAL_ENUM, DialConstant.DIAL_UN_CALL_USER_NAME_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getRoomId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DialConstant.DIAL_ENUM, DialConstant.DIAL_UN_CALL_USER_NAME_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }

        // 发送消息 【开启腾讯视频通话】
        // 组装json
        JSONObject data = new JSONObject();
        data.put("code", EmqCode.appDialWatchVoiceCode);
        // 主键id-->只有这条是接收topic需要用到的
        data.put("imei", reqVO.getImei());
        data.put("roomId", reqVO.getRoomId());
        data.put("callUserId", reqVO.getCallUserId());
        data.put("callUserName", reqVO.getCallUserName());
        data.put("callImage", reqVO.getCallImage());
        // 推送绑定围栏topic给设备
        publishService.sendToMqtt(data.toJSONString(), EmqCode.sendTopic + reqVO.getImei() + EmqCode.endTopic);
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }


    /**
     * 拍照上传
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/photoUpload", method = RequestMethod.POST)
    @OperationAnnotation(content = "拍照上传")
    public BaseResponse photoUpload(@RequestBody FenVO fenVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        String imei = fenVO.getImei();
        if (!OptionalBean.ofNullable(imei).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_IMEI_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        // 发送消息 【拍照上传】
        // 组装json
        JSONObject data = new JSONObject();
        data.put("code", EmqCode.photoUploadCode);
        // 主键id-->只有这条是接收topic需要用到的
        data.put("imei", imei);
        // 推送绑定围栏topic给设备
        publishService.sendToMqtt(data.toJSONString(), EmqCode.sendTopic + imei + EmqCode.endTopic);
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    /**
     * 立即重启
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/reBoot", method = RequestMethod.POST)
    @OperationAnnotation(content = "立即重启")
    public BaseResponse reBoot(@RequestBody FenVO fenVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;

        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        String imei = fenVO.getImei();
        if (!OptionalBean.ofNullable(imei).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_IMEI_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        JSONObject data = new JSONObject();
        data.put("code", EmqCode.rebootCode);
        // 主键id-->只有这条是接收topic需要用到的
        data.put("imei", imei);
        // 推送立即重启topic给设备
        publishService.sendToMqtt(data.toJSONString(), EmqCode.sendTopic + imei + EmqCode.endTopic);
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.REBOOT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }


    /**
     * 控制头盔灯开关
     *
     * @param lightVO
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/controlLight", method = RequestMethod.POST)
    @OperationAnnotation(content = "控制头盔灯开关")
    public BaseResponse controlLight(@RequestBody LightVO lightVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        String imei = lightVO.getImei();
        if (!OptionalBean.ofNullable(imei).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_IMEI_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        // 发送消息 【控制头盔灯开关】
        // 组装json
        JSONObject data = new JSONObject();
        data.put("code", EmqCode.controlLight);
        // 主键id-->只有这条是接收topic需要用到的
        data.put("imei", imei);
        data.put("isOpen", lightVO.getIsOpen());
        // 推送控制头盔灯开关topic给设备
        publishService.sendToMqtt(data.toJSONString(), EmqCode.sendTopic + imei + EmqCode.endTopic);
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    /**
     * 消息群发
     * 前端不愿意订阅一个主题，那就循环发算了
     *
     * @param reqVO
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/massMessaging", method = RequestMethod.POST)
    @OperationAnnotation(content = "消息群发")
    public BaseResponse massMessaging(@RequestBody MassVO reqVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (CollectionUtils.isEmpty(reqVO.getImeis())) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_IMEI_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getContent()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_CONTENT_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        // 推送立即重启topic给设备
        List<String> imeis = reqVO.getImeis();
        imeis.stream().forEach(
                imei -> {
                    // 发送消息 【记录消息群发操作】
                    // 组装json
                    JSONObject data = new JSONObject();
                    data.put("code", EmqCode.massMessaging);
                    // 主键id-->只有这条是接收topic需要用到的
                    data.put("imei", imei);
                    data.put("content", reqVO.getContent());
                    publishService.sendToMqtt(data.toJSONString(), EmqCode.sendTopic + imei + EmqCode.endTopic);
                });
        return setResultSuccess();
    }

    /**
     * 更改菊风视频key
     *
     * @param reqVO
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateApiKey", method = RequestMethod.POST)
    @OperationAnnotation(content = "更改菊风视频key")
    public BaseResponse updateApiKey(@RequestBody LightVO reqVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if(StringUtils.isEmpty(reqVO.getApikeyValue())){
            systemParam = systemParamByCacheService.getValues(VcrInfoConstant.VCRINFO_ENUM, VcrInfoConstant.VCR_NO_APIKEYVALUE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        redisUtils.set("getJFKey",reqVO.getApikeyValue());
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.MODIFY_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    /**
     *  本地录像上传到云-开关
     *
     * @param reqVO
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadSwitch", method = RequestMethod.POST)
    @OperationAnnotation(content = "本地录像上传到云-开关")
    public BaseResponse uploadSwitch(@RequestBody SwitchVO reqVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (!OptionalBean.ofNullable(reqVO.getImei()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_IMEI_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        // 发送消息 【控制头盔灯开关】
        // 组装json
        JSONObject data = new JSONObject();
        data.put("code", EmqCode.uploadSwitchCode);
        // 主键id-->只有这条是接收topic需要用到的
        data.put("imei", reqVO.getImei());
        data.put("isOpen", reqVO.getIsOpen());
        // 推送控制本地录像上传到云-开关topic给设备
        publishService.sendToMqtt(data.toJSONString(), EmqCode.sendTopic + reqVO.getImei() + EmqCode.endTopic);
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    /**
     *  设置本地录像清晰度
     *
     * @param reqVO
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/setUpVideoDefinition", method = RequestMethod.POST)
    @OperationAnnotation(content = "设置本地录像清晰度")
    public BaseResponse setUpVideoDefinition(@RequestBody SetUpVideoDefinitionVO reqVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (!OptionalBean.ofNullable(reqVO.getImei()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_IMEI_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        // 发送消息 【控制头盔灯开关】
        // 组装json
        JSONObject data = new JSONObject();
        data.put("code", EmqCode.setUpVideoDefinition);
        // 主键id-->只有这条是接收topic需要用到的
        data.put("imei", reqVO.getImei());
        // value: 清晰度，取值范围，1-10，
        data.put("value", reqVO.getDefinition());
        // 推送设置本地录像清晰度topic给设备
        publishService.sendToMqtt(data.toJSONString(), EmqCode.sendTopic + reqVO.getImei() + EmqCode.endTopic);
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }
}
